package rulebase;

import java.util.ArrayList;
import java.util.List;

import commondata.IPlayer;
import commondata.ITradeRule;
import commondata.TradeOptionStruct;

public class SalaryMatch implements ITradeRule {

	public void isTradeApplicable(TradeOptionStruct tradeOptionStruct) {

		List<String> result = new ArrayList<String>();
		String message = "";

		double outgoing = getTotalWages(tradeOptionStruct.getFirstTeamPlayers());
		double incoming = getTotalWages(tradeOptionStruct.getSecondTeamPlayers());

		double diff = outgoing - (calculate125(incoming));
		if (diff > 0) {
			message = "Outgoing salaries for "+tradeOptionStruct.getFirstTeam().getTeamName()+" are greater than 125% of incoming salaries. "
					+ "Cut $"
					+ formatDouble(diff)
					+ " M from the outgoing trade value to make this trade successful.";
			result.add(message);
		}
		diff = incoming - (calculate125(outgoing));
		if (diff > 0) {

			message = tradeOptionStruct.getFirstTeam().getTeamName()+" is over cap. Incoming salaries are greater than 125% of outgoing salaries. "
					+ "Cut $"
					+ formatDouble(diff)
					+ " M from the incoming trade value to make this trade successful.";
			result.add(message);

		}
		tradeOptionStruct.getRuleEngineResults().addAll(result);
	}

	private double calculate125(double salary) {
		return salary * 125 / 100;
	}

	private double getTotalWages(List<IPlayer> playerList) {
		double totalWage = 0;

		for (IPlayer player : playerList) {
			totalWage += player.getWage();
		}
		return totalWage;
	}
	
	double formatDouble(double d){
		int in = (int) (d * 1000);
		return ((double)in / 1000);
	}
}
